package com.hfmx.aitonguedemo;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.editText)
    EditText editText;
    @BindView(R.id.button)
    Button button;
    @BindView(R.id.linearLayout)
    LinearLayout linearLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    public void onClick(View view) {
        this.sendByOKHttp();
    }

    /**
     * 发送请求（使用 OKHttp）
     */
    private void sendByOKHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                String devid = "xxxxxx";
                String devsecret = "xxxxxx";
                String url = "https://www.ai-tongue.com/backend/auth/invoker/pwd/signin";
                FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
                formBody.add("devid", devid);//传递键值对参数
                formBody.add("devsecret", devsecret);//传递键值对参数
                Request request = new Request.Builder().url(url).post(formBody.build()).build();
                try {
                    Response response = client.newCall(request).execute();//发送请求
                    String result = response.body().string();
                    JSONObject josn = new JSONObject(result);
                    String access_token = josn.getJSONObject("data").getString("access_token");
                    Log.d("test", "josn: " + access_token);
                    Intent intent = new Intent(MainActivity.this, WebViewActivity.class);
                    intent.putExtra("access_token", access_token);
                    startActivity(intent);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
